/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.mapper.CopeDetilMapper;
import com.jeeplus.modules.fee.mapper.ReceivablesDetailedMapper;
import com.jeeplus.modules.fee.service.CopeService;
import com.jeeplus.modules.fee.service.FeeZzslService;
import com.jeeplus.modules.fee.service.ProfitService;
import com.jeeplus.modules.fee.service.ReceivableService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.mapper.CustomerGoodsControrMapper;
import com.jeeplus.modules.infor.mapper.ReAddressMapper;
import com.jeeplus.modules.infor.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.*;
import com.jeeplus.modules.tms.mapper.InformationsMapper;
import com.jeeplus.modules.tms.mapper.MaterialInformationsMapper;
import com.jeeplus.modules.tms.service.*;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 委托单Controller
 * @author 李超辉
 * @version 2017-12-11
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/planning")
public class PlanningController extends BaseController {

	@Autowired
	private PlanningService planningService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private TransportPlanningService transportPlanningService;
	@Autowired
	private MaterialInformationsMapper materialInformationsMapper;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private TakeAddressService takeAddressService;
	@Autowired
	private TmsWaybillService waybillService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ReceivableService receivableService;
	@Autowired
	private ReceivablesDetailedMapper detailedMapper;
	@Autowired
	private CopeService copeService;
	@Autowired
	private CopeDetilMapper copeDetilMapper;
	@Autowired
	private PriceService priceService;
	@Autowired
	private InformationsMapper informationsMapper;
	@Autowired
	private ReAddressMapper reAddressMapper;
	@Autowired
	private TimeControrService timeControrService;
	@Autowired
	private LnCustomersService lnCustomersService;
	@Autowired
	private CustomerGoodsControrMapper customerGoodsControrMapper;
	@Autowired
	private TailAfterService tailAfterService;
	@Autowired
	private ProfitService  profitService;
	@Autowired
	private SlService slService;
	@Autowired
	private FeeZzslService zzslService;

	@ModelAttribute
	public Planning get(@RequestParam(required=false) String id) {
		Planning entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = planningService.get(id);
		}
		if (entity == null){
			entity = new Planning();
		}
		return entity;
	}
	
	/**
	 * 委托单列表页面
	 */
	@RequiresPermissions("tms:planning:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/planningList";
	}
	
		/**
	 * 委托单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:planning:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Planning planning, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){planning.setProjectName(pro);}
		Page<Planning> page = planningService.findPage(new Page<Planning>(request, response), planning);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑委托单表单页面
	 */
	@RequiresPermissions(value={"tms:planning:view","tms:planning:add","tms:planning:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Planning planning, Model model) {
		if(planning.getIsNewRecord()){
			planning.setStatus("已创建");
			planning.setDate(new Date());
			String pro=UserUtils.getUseroffice();
			if(!pro.equals("总部")){planning.setProjectName(pro);}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			Planning p=new Planning();
			p.setEntrustNumber(code);
			List<Planning> l=planningService.findList(p);
			if(l==null||l.size()<1){
				planning.setEntrustNumber(code+"001"+"YS");
			}else{
				if(l.size()/10==0){
					planning.setEntrustNumber(code+"00"+(l.size()+1)+"YS");
				}else
				if(l.size()/100==0){
					planning.setEntrustNumber(code+"0"+(l.size()+1)+"YS");
				}else{planning.setEntrustNumber(code+(l.size()+1)+"YS");}

			}
		}
		List<Map<String,Object>> list=jdbc.queryForList("SELECT type ,sum(gross) as gross,SUM(weight)as weight, SUM(volume)  as volume,depot FROM `tms_informations` where planning='"+planning.getId()+"' GROUP BY type,depot;");
		NumberFormat nf = NumberFormat.getInstance();
		for(Map<String,Object> m:list){
			m.put("weight",nf.format(Double.parseDouble(m.get("weight")+"")));
			m.put("volume",nf.format(Double.parseDouble(m.get("volume")+"")));
			m.put("depot",takeAddressService.get(m.get("depot")+"").getStore());
		}
		model.addAttribute("list", list);
		model.addAttribute("planning", planning);
		return "modules/tms/planningForm";
	}

	/**
	 * 保存委托单
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxJson save(Planning planning, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, planning)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(planning.getIsNewRecord()){
			planning.setJftj("不满足");
		}
		if(planning.getShipmentNumbers()==null||planning.getContractDistance().getId()==null||planning.getShipmentNumbers().length()<1||planning.getSite()==null||planning.getSite().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		for(Informations m:planning.getInformationsList()){
			if(m.getNumber().length()<1||m.getCoding().length()<1||m.getGross().length()<1||m.getDepot()==null||m.getDepot().getStore().length()<1){
				j.setSuccess(false);
				j.setMsg("请检查确定无误后保存！");
				return j;
			}
		}
		//新增或编辑表单保存
		boolean bol=false;
		if(planning.getId().length()<2){
             bol=true;
		}
		Project pr=projectService.findUniqueByProperty("name",planning.getUnitName());
		if(planning.getType().contains("调拨")&&pr==null){
			j.setMsg("请检查收货地址！");
			j.setSuccess(false);
			return  j;
		}

		if(bol){
//			Price p=new Price();
//			p.setMo(planning.getWorkType());
//			p.setProjectName(projectService.findUniqueByProperty("name",UserUtils.getUseroffice()));
			String ii=planning.getArrive().getId();
			if(ii.length()<1){
				j.setMsg("该地址没有维护到站地");
				j.setSuccess(false);
				return j;
			}

			Price price=new Price();
			price.setProjectName(projectService.findUniqueByProperty("name",planning.getProjectName()));
			price.setMo(planning.getWorkType());
			price.setAddress(planning.getArrive());
			price.setStart(planning.getContractDistance());
			price.setMin(planning.getDate());
			price.setMax(planning.getDate());
			List<Price> l=priceService.findList(price);
			if(l==null||l.size()<1){
				j.setMsg("请先维护运价");
				j.setSuccess(false);
				return j;
			}


		}
		planningService.save(planning);//保存
		double d=0.0;
		NumberFormat nf = NumberFormat.getInstance();
		for(Informations i:planning.getInformationsList()){
			d+=Double.parseDouble(i.getWeight());
		}
		planning.setWeight(Double.parseDouble(nf.format(d).replaceAll(",","")));

			planningService.save(planning);//保存
		j.setSuccess(true);
		j.setMsg("保存委托单成功");
		return j;
	}
	
	/**
	 * 删除委托单
	 */
	@ResponseBody
	@RequiresPermissions("tms:planning:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Planning planning, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
//			TransportPlanning t=transportPlanningService.findUniqueByProperty("entrust_number",planning.getEntrustNumber());
//		   transportPlanningService.delete(t);
		planningService.delete(planning);
		j.setMsg("删除委托单成功");
		return j;
	}
	
	/**
	 * 批量删除委托单
	 */
	@ResponseBody
	@RequiresPermissions("tms:planning:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			planningService.delete(planningService.get(id));
		}
		j.setMsg("删除委托单成功");
		return j;
	}


	/**
	 * 批量取消计费
	 */
	@ResponseBody
	@RequestMapping(value = "qxjf")
	public AjaxJson qxjf(String ids, RedirectAttributes redirectAttributes) {
		String[] i=ids.split(",");
		for(String id:i){
			Planning p=planningService.get(id);
			Receivable r=receivableService.findUniqueByProperty("pid",id);
		if(r.getStatus().equals("2")){
			AjaxJson j = new AjaxJson();
			j.setSuccess(false);
			j.setMsg("费用已确认，不能取消计费");
			return j;
		}
			receivableService.delete(r);
			Cope cope=copeService.findUniqueByProperty("pid",id);
			copeService.delete(cope);
			Profit pro=profitService.findUniqueByProperty("pid",id);
			profitService.delete(pro);
		p.setStatus("已生成计划");
		planningService.save(p);
			}

		AjaxJson j = new AjaxJson();
		j.setSuccess(true);
		j.setMsg("取消计费成功");
		return j;
	}
	/**
	 * 批量计费
	 */
	@ResponseBody
	@Transactional(readOnly = false)
	@RequestMapping(value = "jf")
	public AjaxJson jf(String ids, RedirectAttributes redirectAttributes)throws Exception {

		String pro= UserUtils.getUseroffice();
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		boolean bol=true;
		for(String id : idArray){
			Planning p=planningService.get(id);
			String ii=p.getArrive().getId();
			if(ii.length()<1){
				j.setMsg("该地址没有维护到站地");
				j.setSuccess(false);
				return j;
			}

			if(!p.getStatus().equals("已生成计划")){
				bol=false;
				break;
			}else{
				TransportPlanning tr=transportPlanningService.findUniqueByProperty("pid",p.getId());
			    if(tr.getPlanStatus().equals("计划完成")){
					TmsWaybill tw=new TmsWaybill();
					tw.setPid(p.getId());
					List<TmsWaybill> list= waybillService.findList(tw);
					if(list==null||list.size()<1){
						bol=false;
						break;
					}else{
						for(TmsWaybill twb:list){
							if(twb.getHtzt().equals("0")){
                             bol=false;
							}
						}
						if(!bol){
							break;
						}
					}
				}else{
					bol=false;
					break;
				}
			}

		}
		if(bol){
			for(String id : idArray){

				Planning p=planningService.get(id);

				//创建应收
				Receivable r=new Receivable();
				r.setPid(id);
				r.setProject(UserUtils.getUseroffice());
				r.setEntrustNumber(p.getEntrustNumber());
				r.setShipmentNumbers(p.getShipmentNumbers());
				r.setMileage(p.getDistance());
				Price price=new Price();
				price.setProjectName(projectService.findUniqueByProperty("name",p.getProjectName()));
				price.setMo(p.getWorkType());
				price.setAddress(p.getArrive());
				price.setStart(p.getContractDistance());
				price.setMin(p.getDate());
				price.setMax(p.getDate());
				List<Price> l=priceService.findList(price);
				if(l==null||l.size()<1){
					j.setMsg("请先维护运价");
					j.setSuccess(false);
					return j;
				}
                Price pr1=l.get(0);
				String po="";
				String add="";
				if(pr1.getWidth1()!=null &&pr1.getWidth1().getWidth()!=null){
				if(pr1.getWidth1().getWidth().equals(p.getWidth())){
					po=pr1.getPrice1();
					add=pr1.getAd1();
				}}
				if(pr1.getWidth2()!=null &&pr1.getWidth2().getWidth()!=null){
				if(pr1.getWidth2().getWidth().equals(p.getWidth())){
					po=pr1.getPrice2();
					add=pr1.getAd2();
				}}
				if(pr1.getWidth3()!=null && pr1.getWidth3().getWidth()!=null){
				if(pr1.getWidth3().getWidth().equals(p.getWidth())){
					po=pr1.getPrice3();
					add=pr1.getAd3();
				}}
				if(pr1.getWidth4()!=null &&pr1.getWidth4().getWidth()!=null){
				if(pr1.getWidth4().getWidth().equals(p.getWidth())){
					po=pr1.getPrice4();
					add=pr1.getAd4();
				}}
				if(pr1.getWidth5()!=null &&pr1.getWidth5().getWidth()!=null){
				if(pr1.getWidth5().getWidth().equals(p.getWidth())){
					po=pr1.getPrice5();
					add=pr1.getAd5();
				}}
				receivableService.save(r);
				List<Informations> list=p.getInformationsList();
				double pri=Double.parseDouble(po);
				String ad=add;
				if(ad.length()<1){
					ad="0";
				}
				double ppp=Double.parseDouble(ad);
				String th="";
				Double d=0.0;
				NumberFormat nf = NumberFormat.getInstance();
				Double gc=0.0;
				for(Informations i:list){
					Goods g=goodsService.get(i.getGoods().getId());
					if(g.getType().getName().equals("广促品")){
							gc=Double.parseDouble(pr1.getPrice());
					}
				}
				double pr=0.0;
               for(Informations i:list){
               	  if(!th.contains(i.getNumber())){
               	  	th=th+i.getNumber()+",";
				  }
                   ReceivablesDetailed detailed=new ReceivablesDetailed();
                   detailed.setReceivables(r);
                   detailed.setId(UUID.randomUUID().toString().replace("-",""));
				   Goods g=goodsService.get(i.getGoods().getId());
				   detailed.setGoods(i.getGoods());
				   detailed.setMileage(p.getDistance());
				   detailed.setWeight(i.getWeight());
				   detailed.setCoefficient(g.getMoney());
				   detailed.setVolum(i.getVolume());
				   detailed.setPrice(pri);
				   Double wei=Double.parseDouble(i.getWeight().replaceAll(",",""));
				   Double vo=Double.parseDouble(i.getVolume().replaceAll(",",""));
				   String o=g.getMoney();
				   if(o==""||o==null){
				   	o="0";
				   }

				   Double xs=Double.parseDouble(o);
				   TimeContror timeContror=new TimeContror();
				   timeContror.setPro(UserUtils.getUseroffice());
				   timeContror.setMax(p.getDate());
				   timeContror.setMin(p.getDate());
				   List<TimeContror> timeList=timeControrService.findList(timeContror);
				   Double soft=1.0;
				   int num=0;
				   if(timeList!=null&&timeList.size()>0){
				   	soft=timeList.get(0).getSorft();
				   	num=timeList.get(0).getNum();
				   }
				   ReAddress reAddress=new ReAddress();
				   reAddress.setProjectName(UserUtils.getUseroffice());
				   String name=p.getSite();
				   String a="";
				   String b="";
				   String cc="";
				   String dd="";
				   String e="";
				   String f="";
				   String gg="";
				   String n="";
				   boolean bo=true;
				   if(bo){
					   if(name.indexOf("\\")>=0){
						   a=name.substring(0,name.indexOf("\\"));
						   name=name.substring(name.indexOf("\\")+1);
					   }else{
						   n=name;
						   bo=false;
					   }}
				   if(bo){
					   if(name.indexOf("\\")>=0){
						   b=name.substring(0,name.indexOf("\\"));
						   name=name.substring(name.indexOf("\\")+1);
					   }else{
						   n=a+"\\\\"+name;
						   bo=false;
					   }}
				   if(bo){
					   if(name.indexOf("\\")>=0){
						   cc=name.substring(0,name.indexOf("\\"));
						   name=name.substring(name.indexOf("\\")+1);
					   }else{
						   n=a+"\\\\"+b+"\\\\"+name;
						   bo=false;
					   }}
				   if(bo){
					   if(name.indexOf("\\")>=0){
						   dd=name.substring(0,name.indexOf("\\"));
						   name=name.substring(name.indexOf("\\")+1);
					   }else{
						   n=a+"\\\\"+b+"\\\\"+cc+"\\\\"+name;
						   bo=false;
					   }}
				   if(bo){
					   if(name.indexOf("\\")>=0){
						   e=name.substring(0,name.indexOf("\\"));
						   name=name.substring(name.indexOf("\\")+1);
					   }else{
						   n=a+"\\\\"+b+"\\\\"+cc+"\\\\"+dd+"\\\\"+name;
						   bo=false;
					   }}
				   if(bo){
					   if(name.indexOf("\\")>=0){
						   f=name.substring(0,name.indexOf("\\"));
						   name=name.substring(name.indexOf("\\")+1);
					   }else{
						   n=a+"\\\\"+b+"\\\\"+cc+"\\\\"+dd+"\\\\"+e+"\\\\"+name;
						   bo=false;
					   }}
				   if(bo){
					   if(name.indexOf("\\")>=0){
						   gg=name.substring(0,name.indexOf("\\"));
						   name=name.substring(name.indexOf("\\")+1);
					   }else{
						   n=a+"\\\\"+b+"\\\\"+cc+"\\\\"+d+"\\\\"+e+"\\\\"+f+"\\\\"+name;
					   }}
				   reAddress.setAddress(n);
				   reAddress=reAddressMapper.findList(reAddress).get(0);
				   reAddress=reAddressMapper.get(reAddress.getId());
				   LnCustomers ln=lnCustomersService.get(reAddress.getLnCustomers().getId());
				   CustomerGoodsContror c=new CustomerGoodsContror();
				   c.setCustomer(ln);
				   c.setGoods(g);
				   c.setMin(p.getDate());
				   c.setMax(p.getDate());
				   List<CustomerGoodsContror> colist=customerGoodsControrMapper.findList(c);
				   Double sf=1.0;
				   Integer num1=0;
				   if(colist!=null&&colist.size()>0){
				   	sf=colist.get(0).getSorft();
				   	num1=colist.get(0).getNum();
				   }
                detailed.setSorft(soft);
				   detailed.setNum(num);
				   detailed.setSoft(sf);
				   detailed.setNum1(num1);
                 Double  pri1=(pri*soft+num)*sf+num1;
				    pr=pri1*wei*xs;
				   if(g.getType().getName().equals("广促品")){
					   pr=gc*vo*xs;
					   detailed.setPrice(gc);
				   }
				   d+=pr;
				   detailed.setFreight(nf.format(pr));
                  detailedMapper.insert(detailed);
			   }

			   r.setPrice(pri+"");
			   r.setStatus("1");
               r.setSurplus(nf.format(d+ppp).replaceAll(",",""));
               r.setThdh(th);

               r.setReceived("0");
				FeeZzsl f=new FeeZzsl();
				f.setPro(UserUtils.getUseroffice());
				String sll=zzslService.findList(f).get(0).getSl();
				r.setSl(sll);
				Double hs=(d+ppp)*(1+Double.parseDouble(sll));
				r.setHs(nf.format(hs).replaceAll(",",""));
               r.setFreight(nf.format(hs).replaceAll(",",""));

               r.setWeight(nf.format(p.getWeight()).replaceAll(",",""));
               r.setArrive(p.getArrive().getName());
               r.setCompany(p.getUnitName());
               r.setStart(p.getContractDistance().getName());
               r.setDate(p.getDate());
               r.setWidth(p.getWidth());
               r.setSite(p.getSite());
               r.setRemarks(p.getArriveProvince());
               r.setAd(0.0);
               receivableService.save(r);
                   //创建应付
				Cope cope=new Cope();
				cope.setEntrustNumber(p.getEntrustNumber());
				cope.setShipmentNumbers(p.getShipmentNumbers());
				cope.setDate(p.getDate());
				cope.setThdh(th);
				cope.setPid(id);
				cope.setStart(p.getContractDistance().getName());
				cope.setArrive(p.getArrive().getName());
				cope.setCompany(p.getUnitName());
				cope.setProject(UserUtils.getUseroffice());
				copeService.save(cope);
				TmsWaybill tw=new TmsWaybill();
				tw.setShipmentNumbers(p.getShipmentNumbers());
				List<TmsWaybill> li= waybillService.findList(tw);
				Double aa=0.0;
				Double bb=0.0;
				Double cc=0.0;
				Double ddd=0.0;
				Double ee=0.0;
				Double ff=0.0;
				for(TmsWaybill b:li){
					b=waybillService.get(b.getId());
					Double dddd=0.0;
					Double eee=0.0;
					Double fff=0.0;
					for(TmsAdditionalCharge charge: b.getTmsAdditionalChargeList()){
                        if(charge.getBalanceType().contains("防护用品支出")){
                                 dddd+=Double.parseDouble(charge.getMoney());
						}
						if(charge.getBalanceType().contains("装卸费支出")){
							eee+=Double.parseDouble(charge.getMoney());
						}
						if(charge.getBalanceType().contains("其他支出")){
							fff+=Double.parseDouble(charge.getMoney());
						}

					}
					ddd+=dddd;
					ee+=eee;
					ff+=fff;
					CopeDetil c=new CopeDetil();
					c.setBill(b.getCode());
					c.setCope(cope);
					c.setDriver(b.getDriverName());
					c.setTruck(b.getPlateNumber());
					b=waybillService.get(b.getId());
                    int a=0;
                    double dd=0.0;
					for(TmsMaterialsInformation t:b.getTmsMaterialsInformationList()){
						int amount=Integer.parseInt(t.getLoadingQuantity());
						Goods g=goodsService.get(t.getName().getId());
						int bl=Integer.parseInt(g.getProportion());
						int ccc=amount/bl;
						a+=ccc;
						dd+=Double.parseDouble(t.getWeight().replaceAll(",",""));
					}
					c.setWeight(nf.format(dd));
					c.setNumber(a+"");
					c.setDate(b.getFhrq());
//					Date date=tailAfterService.findUniqueByProperty("bill", b.getId()).getThDepartureTime();
//                    c.setDate(date);
					c.setForwardingPrice(b.getForwardingPrice());
					c.setFreight(b.getFreight());
					c.setKdPayment(b.getKdPayment());
					c.setLoadingPayment(b.getLoadingPayment());
					c.setReceiptCalculate(b.getReceiptCalculate());
					c.setRentingCost(b.getRentingCost());
					c.setTotalCost(b.getTotalCost());

					c.setFhyp(dddd+"");
					c.setZxf(eee+"");
					c.setQt(fff+"");
					c.setId(UUID.randomUUID().toString().replace("-",""));
					copeDetilMapper.insert(c);
					aa+=Double.parseDouble(b.getTotalCost());
					bb+=Double.parseDouble(b.getRentingCost());
					cc+=Double.parseDouble(b.getFreight());
				}
				cope.setCarCost(bb+"");
				cope.setFreight(cc+"");
				cope.setContractCost(aa+"");
				cope.setFhyp(ddd+"");
				cope.setZxf(ee+"");
				cope.setQt(ff+"");
				copeService.save(cope);


               p.setStatus("已计费");
               planningService.save(p);
				DecimalFormat df = new DecimalFormat("0.00%");
				Profit profit=new Profit();
				profit.setShipmentNumbers(r.getShipmentNumbers());
				profit.setDate(r.getDate());
				profit.setSr(r.getFreight());
				profit.setNumber(r.getThdh());
				profit.setYfzc(cope.getFreight());
				profit.setCode(p.getEntrustNumber());
				profit.setFhyp(cope.getFhyp());
				profit.setZxf(cope.getZxf());
				profit.setQt(cope.getQt());
				Double zzc=Double.parseDouble(cope.getFreight())+Double.parseDouble(cope.getFhyp())+Double.parseDouble(cope.getZxf())+Double.parseDouble(cope.getQt());
				profit.setZzc(nf.format(zzc).replaceAll(",",""));
				Sl sl=slService.findUniqueByProperty("pro",UserUtils.getUseroffice());
				Double ssl=Double.parseDouble(slService.get(sl.getId()).getSl());
				Double sj=Double.parseDouble(r.getFreight())*ssl;
				profit.setSj(nf.format(sj).replaceAll(",",""));
				Double lr=Double.parseDouble(profit.getSr())-Double.parseDouble(profit.getZzc())-sj;
				profit.setLr(nf.format(lr).replaceAll(",",""));
				profit.setLrl(df.format((lr/Double.parseDouble(profit.getSr()))));
				profit.setPro(UserUtils.getUseroffice());
				profit.setPid(r.getPid());
				profit.setQyd(r.getStart());
				profit.setDzs(r.getRemarks());
				profit.setDzd(r.getArrive());
				profit.setRemarks(r.getWeight());
				profit.setSl(sl.getSl());
				profitService.save(profit);
			}

			j.setMsg("计费成功");
			return j;
		}else {
			j.setMsg("请选择未结算且已完成的订单！");
			return j;
		}

	}

	@RequestMapping(value = "yl")
	public String yl(){
		return "modules/tms/yl";
	}


	/**
	 * 生成计划
	 */
	@ResponseBody
	@RequestMapping(value = "scjh")
	public AjaxJson scjh(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			Planning p=planningService.get(id);
			if(p.getStatus().equals("已创建")){
					TransportPlanning planning=new TransportPlanning();
			planning= (TransportPlanning) CopyUtil.Copy(planning,p,false);
			planning.setWf(p.getWeight());
			planning.setArrive(p.getArrive().getName());
			planning.setRemarks(p.getRemarks());
			planning.setContractDistance(p.getContractDistance().getName());
			planning.setPlanStatus("未计划");
			planning.setPid(id);
					planning.setStatus("已创建");
							transportPlanningService.save(planning);
			List<Informations> l=p.getInformationsList();
			for(Informations inf:l){
				MaterialInformations m=new MaterialInformations();
				m= (MaterialInformations) CopyUtil.Copy(m,inf,false);
				m.setTransportPlanning(planning);
				m.setVehicleQuantity("0");
				m.setRemain(m.getGross());
				m.setDepot(inf.getDepot().getStore());
				m.setId(UUID.randomUUID().toString().replace("-",""));
				materialInformationsMapper.insert(m);
			}
			p.setStatus("已生成计划");
					planningService.save(p);}
	}
		j.setMsg("生成计划成功");
				return j;
}


	/**
	 * 取消运输计划
	 */
	@ResponseBody
	@RequestMapping(value = "qxjh")
	@Transactional
	public AjaxJson qxjh(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
			Planning p=planningService.get(ids);
		    TransportPlanning pla=new TransportPlanning();
		    pla.setShipmentNumbers(p.getShipmentNumbers());
		    pla.setProjectName(UserUtils.getUseroffice());
		   TransportPlanning planning= transportPlanningService.findUniqueByProperty("pid",ids);

			   if(!planning.getPlanStatus().contains("未")){
				   j.setMsg("请先将计划取消配载！");

			   }else{ transportPlanningService.delete(planning);
				   p.setStatus("已创建");
				   planningService.save(p);

				   j.setMsg("取消计划成功！");
				   }



		return j;

	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("tms:planning:export")
    @RequestMapping(value = "export")
    public String exportFile(Planning planning, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "委托单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
           String pro=(UserUtils.getUseroffice());
           if(pro!="总部"){
            planning.setProjectName(pro);}
            Page<Planning> page = planningService.findPage(new Page<Planning>(request, response, -1), planning);
            List<ImportPlaning> l=new ArrayList<ImportPlaning>();
            for(Planning p:page.getList()){
            	p=planningService.get(p.getId());
            	List<Informations> list=p.getInformationsList();
            	for(Informations i:list){
            		ImportPlaning im=new ImportPlaning();
            		im.setShipmentNumbers(p.getShipmentNumbers());
            		im.setNumber(i.getNumber());
            		im.setCoding(i.getCoding());
            		im.setDepot(i.getDepot());
            		im.setStart(p.getContractDistance());
            		im.setSite(p.getSite());
            		im.setAmount(i.getGross());
            		im.setWidth(p.getWidth());
            		l.add(im);
				}
			}
    		new ExportExcel("委托单", ImportPlaning.class).setDataList(l).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出委托单失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/tms/planning/list?repage";
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Planning detail(String id) {
		return planningService.get(id);
	}



	public void inset(Planning planning,ImportPlaning p){
		Informations i=new Informations();
		i.setPlanning(planning);
		List<Informations> li=informationsMapper.findList(i);
		if(li!=null&&li.size()>0){
			i.setIdx(li.size());
		}else{
			i.setIdx(0);
		}
		i.setGross(p.getAmount());
		i.setCoding(p.getCoding());
		Goods g=new Goods();
		g.setProject(UserUtils.getUseroffice());
		g.setCode(p.getCoding());
		g=goodsService.findList(g).get(0);
		g=goodsService.get(g.getId());
		i.setGoods(g);
		i.setSpecification(g.getSpecifications());
		i.setType(g.getType().getName());
		i.setPacking(g.getPacking());
		i.setNumber(p.getNumber());
		NumberFormat nf = NumberFormat.getInstance();
		Double d =Double.parseDouble(p.getAmount())*Double.parseDouble(g.getGrossWeight());
		Double v =Double.parseDouble(p.getAmount())*Double.parseDouble(g.getVolume());
		i.setWeight(nf.format(d).replaceAll(",",""));
		i.setVolume(nf.format(v).replaceAll(",",""));
		i.setDepot(p.getDepot());
		i.setId(UUID.randomUUID().toString().replace("-",""));
		informationsMapper.insert(i);
	}
	/**
	 * 导入Excel数据

	 */
	@Transactional(readOnly = false)
	@RequiresPermissions("tms:planning:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file,Model model, RedirectAttributes redirectAttributes) {
		try {
			NumberFormat nf = NumberFormat.getInstance();
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ImportPlaning> list = ei.getDataList(ImportPlaning.class);
			for (ImportPlaning p : list){
				try{
					String zy=p.getShipmentNumbers();
					Planning planning=new Planning();
					planning.setJftj("不满足");
					planning.setShipmentNumbers(p.getShipmentNumbers());
					planning.setProjectName(UserUtils.getUseroffice());
					planning.setTransportMode("汽运");
					List<Planning> l=planningService.findList(planning);
					if(l!=null&&l.size()>0){
						planning=l.get(0);
						if(!planning.getStatus().equals("已创建")){
							addMessage(redirectAttributes, "导入委托单失败！失败信息：有相同的装运号存在，且已进行操作");
							return "redirect:"+Global.getAdminPath()+"/tms/planning/?repage";
						}
                        inset(planning,p);
						save(planningService.get(planning.getId()),model,redirectAttributes );
					}else {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
						String code=UserUtils.getUserAre()+sdf.format(new Date());
						Planning pp=new Planning();
						pp.setEntrustNumber(code);
						planning.setWidth(p.getWidth());
						List<Planning> ll=planningService.findList(pp);
						if(ll==null||ll.size()<1){
							planning.setEntrustNumber(code+"001"+"YS");
						}else{
							if(ll.size()/10==0){
								planning.setEntrustNumber(code+"00"+(ll.size()+1)+"YS");
							}else
							if(ll.size()/100==0){
								planning.setEntrustNumber(code+"0"+(ll.size()+1)+"YS");
							}else{planning.setEntrustNumber(code+(ll.size()+1)+"YS");}

						}

						planning.setDate(new Date());
						planning.setContractDistance(p.getStart());
						ReAddress r=new ReAddress();
						r.setProjectName(UserUtils.getUseroffice());
						r.setAddress(p.getSite());
						r=reAddressMapper.findList(r).get(0);
						r=reAddressMapper.get(r.getId());
						planning.setUnitName(r.getLnCustomers().getCompany());
						planning.setUnitConfirmor(r.getPerson());
						planning.setPhone(r.getPhone());
						planning.setSite(p.getSite());
						planning.setArriveCity(r.getCity());
						planning.setArriveProvince(r.getProvince());
						planning.setArrive(r.getArrive());
						planning.setDistance(r.getMileage());
						planning.setTransitLines(r.getLine());
						planning.setProjectName(UserUtils.getUseroffice());
						planning.setStatus("已创建");
						planning.setType("销售订单");
						planning.setWorkType("常规");
						planning.setKhyq(r.getNeeds());
						planningService.save(planning);
						inset(planning,p);
						save(planningService.get(planning.getId()),model,redirectAttributes );
					}

					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条委托单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条委托单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入委托单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/planning/?repage";
    }
	
	/**
	 * 下载导入委托单数据模板
	 */
	@RequiresPermissions("tms:planning:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "委托单数据导入模板.xlsx";
    		List<ImportPlaning> list = Lists.newArrayList();
    		new ExportExcel("委托单数据", ImportPlaning.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/planning/?repage";
    }
	

}